package com.example.juc.until;
//线程通信 +1 -1 循环
class tx{

    private static int number = 0;
    //+1
    public synchronized void jia() throws InterruptedException {
        if(number!=0){
            this.wait();  //如果不是0需要等待 -1线程方法执行
        }
        number++;
        System.out.println(Thread.currentThread().getName()+":::"+number);
        this.notifyAll(); //唤醒  通知-1方法
    }

    //-1
    public synchronized void jian() throws InterruptedException {
        if(number!=1){
            this.wait();  //如果不是1需要等待 +1线程方法执行
        }
        number--;
        System.out.println(Thread.currentThread().getName()+":::"+number);
        this.notifyAll();   //唤醒  通知+1方法
    }
}

public class tongxin {
    public static void main(String[] args) {
        tx tx= new tx();

        new Thread(() -> {  //+1
            for (int i = 1; i <=10; i++) {
                try {
                    tx.jia();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(() -> {  //-1
            for (int i = 1; i <=10; i++) {
                try {
                    tx.jian();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
    }
    }

